package login

import (
	"errors"

	"github.com/grafana/grafana/pkg/bus"
	m "github.com/grafana/grafana/pkg/models"
)

var (
	ErrEmailNotAllowed       = errors.New("不满足 email 域所需的条件")
	ErrInvalidCredentials    = errors.New("用户名或密码不正确")
	ErrNoEmail               = errors.New("登录提供商未返回 email 地址")
	ErrProviderDeniedRequest = errors.New("登录提供商拒绝登录请求")
	ErrSignUpNotAllowed      = errors.New("这个适配器不允许注册")
	ErrTooManyLoginAttempts  = errors.New("用户连续错误登录尝试次数过多。登录用户暂时被阻止")
	ErrUsersQuotaReached     = errors.New("用户配额已满")
	ErrGettingUserQuota      = errors.New("获取用户配额时出错")
)

func Init() {
	bus.AddHandler("auth", AuthenticateUser)
	loadLdapConfig()
}

func AuthenticateUser(query *m.LoginUserQuery) error {
	if err := validateLoginAttempts(query.Username); err != nil {
		return err
	}

	err := loginUsingGrafanaDB(query)
	if err == nil || (err != m.ErrUserNotFound && err != ErrInvalidCredentials) {
		return err
	}

	ldapEnabled, ldapErr := loginUsingLdap(query)
	if ldapEnabled {
		if ldapErr == nil || ldapErr != ErrInvalidCredentials {
			return ldapErr
		}

		err = ldapErr
	}

	if err == ErrInvalidCredentials {
		saveInvalidLoginAttempt(query)
	}

	if err == m.ErrUserNotFound {
		return ErrInvalidCredentials
	}

	return err
}
